package com.xyp.danmu.api.impl;

import com.xyp.danmu.api.IDanmuController;
import com.xyp.danmu.model.DanmuRequest;
import com.xyp.danmu.model.DanmuResp;
import com.xyp.danmu.model.Message;
import com.xyp.danmu.model.Setting;
import com.xyp.danmu.utils.DateUtils;
import com.xyp.danmu.utils.JsonMapper;
import com.xyp.danmu.utils.RedisDBHelperImpl;
import com.xyp.danmu.utils.StaticUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xyp
 * @version 2019-03-09 13:42
 * @description DanmuControllerImpl
 */
@RestController
public class DanmuControllerImpl implements IDanmuController{
    @Autowired
    private RedisDBHelperImpl redisDBHelper;

    @Override
    public List<Message> getMsgList(@RequestBody DanmuRequest request) {
        int len=redisDBHelper.getLenByKey(StaticUtils.CURRENT_MSG).intValue();
        int startPoint=0;
        if(len<=600){
            startPoint=len/2;
        }else {
            startPoint=startPoint-300;
        }

        List<String> list=redisDBHelper.getListPage(StaticUtils.CURRENT_MSG,startPoint,len);


        List<Message> messageList=new LinkedList<>();
        for(String json:list){
            Message msg= (Message) JsonMapper.fromJsonString(json,Message.class);
//            "https://apic.douyucdn.cn/upload/"+msg.ic+".jpg";
            msg.setIc("https://apic.douyucdn.cn/upload/"+msg.getIc()+".jpg");
            msg.setDate(DateUtils.stringToFullDate(msg.getTime()));
            msg.setDate(DateUtils.stringToFullDate(msg.getTime()).split(" ")[1]);
            messageList.add(msg);
        }
        List<Message> fList=messageList.stream().filter(msg->(msg.getLv()>=request.getStartLevel())).collect(Collectors.toList());
        if(request.getLimit()==0){
            request.setLimit(10);
        }
        int start=request.getStart()*request.getLimit();
        int end=start+request.getLimit();
        if(end>fList.size()) {
            end=fList.size();
        }
        return fList.subList(start,end);
    }

    @Override
    public DanmuResp<Setting> updateSetting(@RequestBody Setting setting) {
        //TODO 转为json  遍历json键字对，写入数据
        redisDBHelper.hashPut(StaticUtils.SETTING,"startLv",String.valueOf(setting.getStartLv()));
        if(setting.getType()!=null){
            redisDBHelper.hashPut(StaticUtils.SETTING,"type",setting.getType());
        }
        return new DanmuResp(true,"",new Object());
    }

    @Override
    public DanmuResp<Setting> getSetting() {
         Map map=redisDBHelper.hashFindAll(StaticUtils.SETTING);
         String json=JsonMapper.toJsonString(map);
         Setting setting= (Setting) JsonMapper.fromJsonString(json,Setting.class);
        return  new DanmuResp<Setting>(true,"获取信息成功",setting);
    }
}
